<?php

namespace app\admin\controller\god;

use app\common\controller\Backend;
use think\Db;

class Student extends Backend
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Student');
        $this->dataLimit = true;
    }


    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $result = ['total' => 0, 'rows' => []];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model->where($where)->count();
            if (intval($total) > 0) {
                $result['total'] = $total;
                $list = $this->model->where($where)->select();
                $iKeyMap = [];
                foreach ($list as $k => $row) {
                    $row['id_type_text'] = '';
                    if (isset($iKeyMap[$row['stu_type']])) {
                        $row['id_type_text'] = $iKeyMap[$row['id_type']];
                    }
                }
                $result['rows'] = $list;
            }

            return json($result);
        }

        return $this->view->fetch();
    }

    private function getEleTypes()
    {
        $stuTypes = model('Enrollment')->column('name', 'id');
        $this->view->assign('stu_types', $stuTypes);

        $sexTypes = [0 => '男', 1 => '女'];
        $this->view->assign('sex_types', $sexTypes);
        // 报考层次
        $rLevelTypes = model('Stureadlevelinfo')->column('name', 'id');
        $this->view->assign('read_level_info', $rLevelTypes);
        // 入学形式
        $eWayTypes = model('Stuenterwayinfo')->column('name', 'id');
        $this->view->assign('enter_way_info', $eWayTypes);
        // 加分方式
        $pWayTypes = model('Pointway')->column('name', 'id');
        $this->view->assign('point_way', $pWayTypes);
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $args = $this->request->post("row/a");
            if (empty($args)) {
                $this->error('参数为空');
            }
            if (empty($args['name'])) {
                $this->error('姓名不能为空');
            }
            Db::startTrans();
            try {
                // 学生信息
                $stuData = $this->getStuInfoByArgs($args);
                $add = $this->model->data($stuData)->save();
                if (empty($add)) {
                    throw new \Exception('添加失败', 9999);
                }
                $stuId = $this->model->id;
                // 学历信息
                $stuEduInfo = $this->getStuEduInfoByArgs($stuId, $args);
                $sedRes = model('Studenteducation')->data($stuEduInfo)->save();
                if (empty($sedRes)) {
                    throw new \Exception('添加失败', 9998);
                }
                // 报读信息
                $stuReadInfo = $this->getStuReadInfoByArgs($stuId, $args);
                $sriRes = model('Studentreadinfo')->data($stuReadInfo)->save();
                if (empty($sriRes)) {
                    throw new \Exception('添加失败', 9997);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getCode() . $e->getMessage());
            }
            $this->success('添加成功', '', $add);
        }


        $this->getEleTypes();
        return $this->view->fetch();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (empty($row)) {
            $this->error('参数异常');
        }
        if ($this->request->isPost()) {
            $this->token();
            $args = $this->request->post("row/a");
            if (empty($args)) {
                $this->error('参数错误');
            }
            Db::startTrans();
            try {
                $data = $this->getStuInfoByArgs($args);
                $save = $this->model->save($data, ['id' => intval($ids)]);
                if (empty($save)) {
                    throw new \Exception('更新失败', 9999);
                }
                // 学历信息
                $stuEduInfo = $this->getStuEduInfoByArgs($ids, $args);
                $sedRes = model('Studenteducation')->save($stuEduInfo, ['stu_id' => $ids]);
                if (empty($sedRes)) {
                    throw new \Exception('更新失败', 9998);
                }
                // 报读信息
                $stuReadInfo = $this->getStuReadInfoByArgs($ids, $args);
                $sriRes = model('Studentreadinfo')->save($stuReadInfo, ['stu_id' => $ids]);
                if (empty($sriRes)) {
                    throw new \Exception('更新失败', 9997);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getCode() . $e->getMessage());
            }
            $this->success('更新成功');
        }
        // 学生数据
        $this->view->assign("row", $row);
        // 学历信息
        $sedu = model('Studenteducation')->where('stu_id', $ids)->find();
        $this->view->assign('sedu', $sedu);
        // 报读信息
        $sri = model('Studentreadinfo')->where('stu_id', $ids)->find();
        $this->view->assign('sri', $sri);

        $this->getEleTypes();
        return $this->view->fetch();
    }

    protected function getStuInfoByArgs($args): array
    {
        return [
            'stu_type' => $args['stu_type'],
            'name' => $args['name'],
            'id_type' => $args['id_type'],
            'id_code' => $args['id_code'],
            'sex' => $args['sex'],
            'birthday' => $args['birthday'],
            'mobile' => $args['mobile'],
            'nation' => $args['nation'],
            'political' => $args['political'],
            'hours_type' => $args['hours_type'],
            'hours_address' => $args['hours_address'],
            'delivery_area' => $args['delivery_address'], // 收货地址
            'delivery_address' => $args['addr_detail'], // 详细地址
            'occupation_type' => $args['occupation_type'],
            'occupation' => $args['occupation'],
            'entry' => $args['entry'],
            'company_address' => $args['company_address'],
            'company_tel' => $args['company_tel'],
            'company_postcode' => $args['company_postcode'],
            'emergency_tel' => $args['emergency_tel'],
            'picture' => $args['picture'],
            'landline' => $args['landline'],
            'email' => $args['email'],
            'qq' => $args['qq'],
            'wechat' => $args['wechat'],
            'work_address' => $args['work_address'],
            'is_marriage' => $args['is_marriage'],
            'remark' => $args['remark'],
            'admin_id' => $this->auth->id,
        ];
    }

    private function getStuEduInfoByArgs($stuId, $args): array
    {
        return [
            'stu_id' => $stuId,
            'old_edu_type' => $args['old_edu_type'],
            'old_edu_name' => $args['old_edu_name'],
            'old_edu_finish' => $args['old_edu_finish'],
            'old_edu_profession' => $args['old_edu_profession'],
            'old_edu_finish_code' => $args['old_edu_finish_code'],
            'is_tv_finish' => $args['is_tv_finish'],
        ];
    }

    private function getStuReadInfoByArgs($stuId, $args): array
    {
        return [
            'stu_id' => $stuId,
            'read_level' => $args['read_level'],
            'enter_way' => $args['enter_way'],
            'enter_grade' => $args['enter_grade'],
            'first_volunteer' => $args['first_volunteer'],
            'second_volunteer' => $args['second_volunteer'],
            'bonus_point_type' => $args['bonus_point_type'],
            'bonus_point' => $args['bonus_point'],
            'fee_type' => $args['fee_type']
        ];
    }
}